package mk.jug.academy.controller;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.springframework.ui.ModelMap;

import mk.jug.academy.exception.BusinessException;
import mk.jug.academy.util.Utils;

/**
 * Base controller for the application.
 *
 * @author Ice.Penov
 */
public class BaseController {
	
	private static final String BUSINESS_ERROR_PAGE = "business.error.page";
	private static final String TECH_ERROR_PAGE = "tech.error.page";
	
	private static final Logger LOG = Logger.getLogger(BaseController.class.getName());
	private static final String SUBJECT = "Error occured in the JUGMK Application";
	
	
	/**
	 * Abstract wrapping class for uniform error handling of controller layer encountered errors.
	 *
	 * @author Ice.Penov
	 */
	protected abstract class ControllerContext {
		private String result;
		
		public abstract String execute();
		
		public ControllerContext(ModelMap map) {
			try {
				result = execute();
			} catch (BusinessException e) {
				map.addAttribute("exception", e);
				StringWriter sw = new StringWriter();
				PrintWriter pw = new PrintWriter(sw, true);
				e.printStackTrace(pw);
				String errorMessage = sw.toString();
				LOG.log(Level.SEVERE, errorMessage);
				map.addAttribute("errorMessage", errorMessage);
				result = BUSINESS_ERROR_PAGE;
			} catch (Exception e) {
				map.addAttribute("exception", e);
				StringWriter sw = new StringWriter();
				PrintWriter pw = new PrintWriter(sw, true);
				e.printStackTrace(pw);
				pw.flush();
				sw.flush();
				String errorMessage = sw.toString();
				LOG.log(Level.SEVERE, errorMessage);
				map.addAttribute("errorMessage", errorMessage);
				Utils.sendMail(new String[] {"jugmk.errors@gmail.com", "JUGMK Errors"}, SUBJECT, errorMessage);
				result = TECH_ERROR_PAGE;
			}
		}				
		
		public String result() {
			return result;
		}
	}

}